<template>
  <div class="business-box">
    <el-row :gutter="20">
      <el-col :span="12">
        <NewCard :isScroll="true" title="来源">
          <el-form
            ref="form"
            :model="sourceList"
            label-width="100px"
            label-position="left"
            v-if="sourceList.data.length > 0"
            v-hasPermi="['base:config:listOpportunities']"
          >
            <el-form-item
              :label="`来源${source.value}`"
              v-for="(source, index) in sourceList.data"
              :key="index"
              :prop="'data.' + index + '.name'"
              :rules="{
                required: true,
                message: `来源${source.value}不能为空`,
                trigger: 'blur',
              }"
            >
              <el-input v-model="source.name"></el-input>
              <p>
                <svg-icon
                  icon-class="add-icon"
                  @click="addSouList(index, source)"
                  v-hasPermi="['base:config:addOpportunities']"
                />
              </p>
              <p>
                <svg-icon
                  icon-class="minus-icon"
                  @click="removeSouList(source, index)"
                  v-hasPermi="['base:config:remove']"
                />
              </p>
            </el-form-item>
          </el-form>
          <el-empty description="暂无内容" v-else></el-empty>
        </NewCard>
      </el-col>
      <el-col :span="12">
        <NewCard :isScroll="true" title="状态">
          <el-form
            ref="form1"
            :model="stateList"
            label-width="100px"
            label-position="left"
            v-if="stateList.data.length > 0"
            v-hasPermi="['base:config:listOpportunities']"
          >
            <el-form-item
              :label="`状态${index + 1}`"
              v-for="(state, index) in stateList.data"
              :key="index"
              :prop="'data.' + index + '.name'"
              :rules="{
                required: true,
                message: `状态${state.value}不能为空`,
                trigger: 'blur',
              }"
            >
              <el-input v-model="state.name"></el-input>
              <p>
                <svg-icon
                  icon-class="add-icon"
                  @click="addStateList(index, state)"
                  v-hasPermi="['base:config:addOpportunities']"
                />
              </p>
              <p>
                <svg-icon
                  icon-class="minus-icon"
                  @click="removeStateList(state, index)"
                  v-hasPermi="['base:config:remove']"
                />
              </p>
            </el-form-item>
          </el-form>
          <el-empty description="暂无内容" v-else></el-empty>
        </NewCard>
      </el-col>
    </el-row>
    <footer class="footer">
      <span class="reset" @click="reset">重设</span>
      <span class="save" @click="saveFn">保存</span>
    </footer>
  </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import SubBtn from "@/wss/components/subBtn.vue";
import {
  getConfigWlistOpportunitiesApi,
  getConfigRemoveApi,
  getAddOpportunitiesApi,
  getConfigEditApi,
} from "@/BMViews/api/base/config.js";
export default {
  name: "Business",
  components: { NewCard, SubBtn },
  data() {
    return {
      // 记录是否是新增或者修改
      length: "",
      //来源
      sourceList: {
        data: [],
      },
      // 状态
      stateList: {
        data: [],
      },

      temSourceList: { data: [] }, // 暂存的来源
      temStateList: { data: [] }, // 暂存的状态
    };
  },
  async created() {
    this.getConfigWlistOpportunitiesFn();
  },
  methods: {
    // 获取分页
    async getConfigWlistOpportunitiesFn() {
      let { code, data } = await getConfigWlistOpportunitiesApi();
      if (code != 200) return;
      const stateList = {
          data: [],
        },
        sourceList = {
          data: [],
        };
      let OpportunitiesList = JSON.parse(JSON.stringify(data));
      this.length = OpportunitiesList.length;

      // 转换分组
      OpportunitiesList.forEach((item) => {
        if (item.type == "o_from") {
          sourceList.data.push(item);

          let tem = JSON.parse(JSON.stringify(item));
          this.temSourceList.data.push(tem);
        } else {
          stateList.data.push(item);

          let tem = JSON.parse(JSON.stringify(item));
          this.temStateList.data.push(tem);
        }
      });
      stateList.data.sort(function (a, b) {
        if (a.value > b.value)
          // 如果 a 大于 b,位置互换
          return 1;
        //否则，位置不变
        else return -1;
      });
      sourceList.data.sort(function (a, b) {
        if (a.value > b.value)
          // 如果 a 大于 b,位置互换
          return 1;
        //否则，位置不变
        else return -1;
      });
      this.sourceList = sourceList;
      this.stateList = stateList;
    },
    // 保存函数
    async saveFn() {
      try {
        await this.$refs.form.validate();
      } catch (error) {
        try {
          await this.$refs.form1.validate();
        } catch (error) {
          throw new Error("中断");
        }
        throw new Error("中断");
      }

      let add = [...this.stateList.data, ...this.sourceList.data];

      let { code, msg } = await getConfigEditApi(add);

      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },

    // 重置按钮
    reset() {
      this.sourceList.data = JSON.parse(
        JSON.stringify(this.temSourceList.data)
      );
      this.stateList.data = JSON.parse(JSON.stringify(this.temStateList.data));
    },

    //添加一条来源
    async addSouList(index, source) {
      // this.sourceList.data.splice(index + 1, 0, {
      //   id: "",
      //   name: "",
      // });

      let { code, msg } = await getAddOpportunitiesApi([
        {
          value: this.sourceList.data.length,
          name: "",
          type: "o_from",
          typeGroup: "opportunities_setting",

          status: "0",
        },
      ]);
      await this.getConfigWlistOpportunitiesFn();
      // this.sourceList.data.push({
      //   value: this.sourceList.data.length,
      //   name: "",
      //   type: "o_from",
      //   typeGroup: "opportunities_setting",

      //   status: "0",
      // });
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },
    //删除一条来源
    async removeSouList(item, index) {
      if(this.sourceList.data.length==1){
        this.$message({type: "warning",message: '不能少于一条',});
        return
      }

      this.sourceList.data.splice(index, 1);
      let { code, msg } = await getConfigRemoveApi(item.id);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },

    //添加一条状态
    async addStateList(index, state) {
      // this.stateList.data.splice(index + 1, 0, {
      //   id: "",
      //   name: "",
      // });

      let { code, msg } = await getAddOpportunitiesApi([
        {
          value: this.stateList.data.length,
          name: "",
          type: "o_status",
          typeGroup: "opportunities_setting",

          status: "0",
        },
      ]);
      await this.getConfigWlistOpportunitiesFn();
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },
    //删除一条状态
    async removeStateList(item, index) {
      if(this.stateList.data.length==1){
        this.$message({type: "warning",message: '不能少于一条',});
        return
      }

      this.stateList.data.splice(index, 1);
      let { code, msg } = await getConfigRemoveApi(item.id);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },
  },
};
</script>

<style scoped lang="scss">
.business-box {
  position: relative;
  /* flex-grow: 1; */
  height: calc(100% - 60px);
}
.business-box .el-row {
  height: 100%;
  margin-bottom: 0;
}
.business-box .el-col,
.business-box .el-card {
  height: 100%;
}
.business-box >>> .el-card__body {
  height: 100%;
}
::v-deep .el-card__body {
  height: 100%;
}
.business-box >>> .el-card__body > div {
  height: calc(100% - 45px);
  overflow-y: auto;
}
.business-box >>> .el-card__body > div::-webkit-scrollbar {
  width: 0;
}
.el-form {
  margin-top: 20px;
  margin-bottom: 80px;
}

::v-deep .el-form .el-form-item__content {
  display: flex;
  align-items: center;
}
::v-deep .el-form .el-form-item__content .el-input {
  width: 88%;
}
::v-deep .el-form .el-form-item__content p {
  width: 4%;
  margin: 0;
  margin-left: 2%;
}
::v-deep .el-form .el-form-item__content p > svg {
  cursor: pointer;
  font-size: 16px;
}
.footer {
  position: absolute;
  align-items: center;
  bottom: 0px;
  width: 100%;
  height: 60px;
  background: #ffffff;
  border-radius: 0px 0px 12px 12px;
  border: 1px solid #ecedf0;
  display: flex;
  justify-content: end;
  line-height: 60px;
  .reset {
    text-align: center;
    line-height: 32px;
    width: 100px;
    height: 32px;
    cursor: pointer;
    margin-right: 10px;

    background: #ffffff;
    border-radius: 20px;
    border: 1px solid #dadee2;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #606e84;
  }
  .save {
    cursor: pointer;

    text-align: center;
    line-height: 32px;
    width: 100px;
    height: 32px;
    background: #f87a23;
    border-radius: 20px;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #ffffff;
  }
}

@media (max-width: 1120px) {
  ::v-deep .el-form .el-form-item__content .el-input {
    width: 82%;
  }
  ::v-deep .el-form .el-form-item__content p {
    width: 7%;
  }
}
</style>